/**
 * Created by change on 2016/4/14.
 * Author by lwh
 * 原生js封装工具集 ---> $http
 */
(function (window) {
    /**
     * 造轮子^^
     * @returns {string}
     */
    String.prototype.trim = function () {
        return this.replace(/(^\s*)|(\s*$)/g, "");
    };

    /**
     * 造轮子^^
     * 模仿jquery的Ajax实现
     * @type {{}}
     */
    var $http = {
        createXMLHttpRequest: function () {
            if (window.ActiveXObject) {
                var aVersions = ["MSXML2.XMLHttp.5.0", "MSXML2.XMLHttp.4.0", "MSXML2.XMLHttp.3.0", "MSXML2.XMLHttp", "Microsoft.XMLHttp"];
                for (var i = 0; i < aVersions.length; i++) {
                    try {
                        return new ActiveXObject(aVersions[i]);
                    } catch (error) {
                        continue;
                    }
                }
            } else if (window.XMLHttpRequest) {
                return new XMLHttpRequest();
            }
            throw new Error("XMLHttp object could not be created.");
        },
        /**
         * ajax方法模拟
         * @param _options = {url,method,data,dataType,success,error}
         */
        ajax: function (_options) {
            var data = null;
            var _xmlHttp = this.createXMLHttpRequest();
            _xmlHttp.open(_options.method, _options.url, true);
            _xmlHttp.withCredentials = true;//放在 open 方法后面比较靠谱
            _xmlHttp.setRequestHeader("cache-control", "no-cache");
            if (_options.method.toUpperCase() == "POST") {
                // 解析参数
                var query = [];
                for (var key in _options.data) {
                    query[query.length] = encodeURI(key) + "=" + encodeURIComponent(_options.data[key]);
                }
                data = query.join('&');
                // POST发送方式的Header
                _xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            }
            _xmlHttp.onreadystatechange = function () {
                if (_xmlHttp.readyState == 4 && _xmlHttp.status == 200) {
                    var responseData = null;
                    switch (_options.dataType.toUpperCase()) {
                        case "json":
                            var jsonObj = null;
                            try {
                                jsonObj = _xmlHttp.responseText;
                                responseData = jsonObj;
                            } catch (error) {
                                throw new Error("Return is not a json object.");
                            }
                            break;
                        case "xml":
                            responseData = _xmlHttp.responseXML;
                            break;
                        case "html":
                            responseData = _xmlHttp.responseText;
                            break;
                        default:
                            responseData = _xmlHttp.responseText;
                            break;
                    }
                    if (typeof (_options.success) != 'undefined') {
                        // 成功，调用自定义的回滚函数
                        _options.success(responseData);
                    }
                }
                else if (_xmlHttp.readyState == 4) {
                    var codes = ['500', '501', '502', '503', '504', '505', '404'];
                    if (codes.join(',').indexOf(_xmlHttp.status.toString()) >= 0 && typeof (_options.error) != 'undefined') {
                        // 错误，调用自定义的回滚函数
                        _options.error(_xmlHttp.status, _xmlHttp.responseText);
                    }
                }
            };
            //开始发送数据
            _xmlHttp.send(data);
        },
        /**
         * get方式请求,参数：{url,dataType,callback}
         * @param _url
         * @param dataType
         * @param callback
         */
        get: function (_url,
                       dataType,
                       callback) {
            this.ajax({
                url: _url,
                dataType: dataType,
                method: "GET",
                success: callback
            });
        },
        /**
         * post方式请求,参数：{url,data,dataType,callback}
         * @param _url
         * @param _data
         * @param dataType
         * @param callback
         */
        post: function (_url,
                        _data,
                        dataType,
                        callback) {
            this.ajax({
                url: _url,
                data: _data,
                method: "POST",
                dataType: dataType,
                success: callback
            });
        },
        /**
         * get方式请求JSON数据
         * @param url
         * @param callback
         */
        getJSON : function (url,callback) {
            this.ajax({
                url : url,
                method : "GET",
                dataType : "json",
                success : callback
            });
        },
        /**
         * post方式请求json数据
         * @param url
         * @param data
         * @param callbalck
         */
        postJSON : function (url,data,callbalck) {
            this.ajax({
                url : url,
                data :  data,
                method : "POST",
                dataType : "json",
                success : callbalck
            });
        }
    };

    // 导出工具对象
   module.exports = $http;

}(window));